package com.ruoyi.merchant.service.impl;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.merchant.domain.Order;
import com.ruoyi.merchant.domain.dto.OrderQueryDTO;
import com.ruoyi.merchant.service.IOrderService;
import com.ruoyi.merchant.utils.MerchantSecurityUtils;
import com.ruoyi.merchant.utils.OrderExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * 订单导出服务
 */
@Slf4j
@Service
public class OrderExportService {

    @Autowired
    private IOrderService orderService;

    /**
     * 导出订单列表
     */
    public byte[] exportOrderList(OrderQueryDTO queryDTO) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        log.info("导出订单列表：merchantId={}", merchantId);

        try {
            // 查询订单列表（不分页，全部导出）
            List<Order> orders = orderService.selectOrderList(queryDTO);
            
            if (orders.isEmpty()) {
                throw new ServiceException("没有可导出的订单");
            }

            log.info("导出订单数量：{}", orders.size());
            
            // 生成Excel
            return OrderExcelUtil.exportOrders(orders);

        } catch (IOException e) {
            log.error("导出订单列表失败", e);
            throw new ServiceException("导出订单列表失败：" + e.getMessage());
        }
    }

    /**
     * 导出订单详情
     */
    public byte[] exportOrderDetail(Long orderId) {
        Long merchantId = MerchantSecurityUtils.getMerchantId();
        log.info("导出订单详情：merchantId={}, orderId={}", merchantId, orderId);

        try {
            // 查询订单详情
            Order order = orderService.selectOrderByOrderId(orderId);
            
            if (order == null) {
                throw new ServiceException("订单不存在");
            }

            if (!merchantId.equals(order.getMerchantId())) {
                throw new ServiceException("无权导出该订单");
            }

            // 生成Excel
            return OrderExcelUtil.exportOrderDetail(order);

        } catch (IOException e) {
            log.error("导出订单详情失败", e);
            throw new ServiceException("导出订单详情失败：" + e.getMessage());
        }
    }
}
